package life.cqq.jwt.interceptor;

import life.cqq.jwt.util.JwsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AutoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
        Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        // 验证token
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isBlank(authorization) || JwsUtils.invalid(authorization)) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.getOutputStream().print("No login");
            return false;
        }
        return true;
    }
}